package cn.edu.zafu.bigdata.lekang.shiyan8;

import java.io.*;
import java.net.*;

public class TimeServer {
    public static void main(String[] args) {
        try {
            // 创建一个DatagramSocket来监听端口
            DatagramSocket serverSocket = new DatagramSocket(9876);
            System.out.println("Time server is running and waiting for requests...");

            // 创建一个byte数组来存储传入的消息
            byte[] receiveData = new byte[1024];
            byte[] sendData = new byte[1024];

            // 无限循环以接收客户端请求
            while (true) {
                // 创建一个DatagramPacket用于接收消息
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                // 提取客户端的IP和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 读取客户端发送的数据
                String sentence = new String(receivePacket.getData(), 0, receivePacket.getLength());
                System.out.println("Client says: " + sentence);

                // 获取当前时间
                String currentTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date());

                // 发送时间给客户端
                sendData = currentTime.getBytes();
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
                System.out.println("Time sent: " + currentTime);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
